﻿using Linq2Rest.Provider;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Xinchen.SOA.GateWay
{
    internal class SOAHttpWebRequestAdapter : IHttpRequest
    {
        public SOAHttpWebRequestAdapter(HttpWebRequest httpWebRequest)
        {
            HttpWebRequest = httpWebRequest;
        }

        /// <summary>
        /// The HttpWebRequest we are adapting to IHttpRequest.
        /// </summary>
        public HttpWebRequest HttpWebRequest { get; private set; }

        /// <summary>
        /// Creates a basic HttpWebRequest that can then be built off of depending on what other functionality is needed.
        /// </summary>
        /// <param name="uri">The uri to send the request to.</param>
        /// <param name="method">The Http Request Method.</param>
        /// <param name="requestMimeType">The MIME type of the data we are sending.</param>
        /// <param name="responseMimeType">The MIME we accept in response.</param>
        /// <returns>Returns an HttpWebRequest initialized with the given parameters.</returns>
        public static HttpWebRequest CreateHttpWebRequest(Uri uri, HttpMethod method, string responseMimeType, string requestMimeType)
        {
            requestMimeType = requestMimeType ?? responseMimeType;

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
            httpWebRequest.Method = method.ToString().ToUpperInvariant();

            if (method == HttpMethod.Post || method == HttpMethod.Put)
            {
                httpWebRequest.ContentType = requestMimeType;
            }

            httpWebRequest.Accept = responseMimeType;

            return httpWebRequest;
        }

        public Stream GetRequestStream()
        {
            return HttpWebRequest.GetRequestStream();
        }

        public Stream GetResponseStream()
        {
            try
            {
                HttpWebRequest.Headers.Add("FromGateway", "1");
                HttpWebRequest.Headers.Add("ApplicationId", ApplicationContext.Current.ApplicationId);
                var response = HttpWebRequest.GetResponse();
                var stream = response.GetResponseStream();
                return stream;
            }
            catch (WebException we)
            {
                using (var sr = new StreamReader(we.Response.GetResponseStream()))
                {
                    throw new Exception("发送请求时出错，地址：" + HttpWebRequest.RequestUri.ToString() + "，错误：" + sr.ReadToEnd());
                }
            }
        }
    }
}
